/**
 * Created by a1 on 2017/11/12.
 */
"use strict";
var fs = require('fs');
var formidable = require('formidable');
var path=require('path');
var gm = require('gm');
var common = require('../models/common.js');
var md5 = require('../models/md5');
var BookModel=require('../models/Book.js');
var AdminModel=require('../models/Admin.js');
var BookupdateModel=require('../models/Bookupdate.js');
var CategorysModel=require('../models/Categorys.js');
var SubcateModel=require('../models/Subcate.js');
var AuthorModel=require('../models/Author.js');
var SystemmenuModel = require('../models/Systemmenu.js');
var SystemsubmenuModel = require('../models/Systemsubmenu.js');

//删除文件夹及文件
function deleteall(path) {
    var files = [];
    if(fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function(file, index) {
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteall(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
}

exports.systemLogin=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let {username,password}=fields;
        AdminModel.findSortOne({username:username},{aid:1},function(err,result){
            if(result==null||result=={}){
                res.json({code:2,msg:'用户名不存在'});
                return;
            }
            var md5psw = md5(md5(password).substring(0,9)+md5(password));
            AdminModel.findSortOne({username:username,password:md5psw},{aid:1},function(err,doc){
                if(doc==null||doc==""){
                    res.json({code:0,msg:'密码错误'});
                    return;
                }
                req.session.susername=username;
                req.session.aid=doc.aid;
                res.json({code:1,msg:'登录成功'});
            });
        });
    });
};
exports.getLogin=function(req,res){
    if(req.session.susername){
        res.json({code:1,msg:'登录中'});
    }else{
        res.json({code:0,msg:'未登录'});
    }
};
exports.getSystemMenu=function(req,res){
    let p1=new Promise(function (resolve,reject) {
        SystemmenuModel.findFn({type:"T"},{smid:1},function(err,docs){
            if(err){
                reject(err);
            }
            resolve(docs);
        });
    });
    p1.then(function(result){
        let arr=[];
        (function bl(i){
            i++;
            if(i==result.length){
                res.json({code:1,msg:"成功",info:{menu:result,submenu:arr}});
                return;
            }else{
                SystemsubmenuModel.findFn({smid:result[i]['smid'],type:"T"},{ssmid:1},function(err,docs1){
                    if(docs1==null){
                        arr.push([]);
                        bl(i);
                    }else{
                        arr.push(docs1);
                        bl(i);
                    }

                });
            }
        })(-1);
    },function(err){
        res.json({code:0,msg:"失败"});
    });
};
exports.getSystemEditMenu=function(req,res){
    let p1=new Promise(function (resolve,reject) {
        SystemmenuModel.findFn({},{smid:1},function(err,docs){
            if(err){
                reject(err);
            }
            resolve(docs);
        });
    });
    p1.then(function(result){
        let arr=[];
        (function bl(i){
            i++;
            if(i==result.length){
                res.json({code:1,msg:"成功",info:{menu:result,submenu:arr}});
                return;
            }else{
                SystemsubmenuModel.findFn({smid:result[i]['smid']},{ssmid:1},function(err,docs1){
                    if(docs1==null){
                        arr.push([]);
                        bl(i);
                    }else{
                        arr.push(docs1);
                        bl(i);
                    }

                });
            }
        })(-1);
    },function(err){
        res.json({code:0,msg:"失败"});
    });
};
exports.getBooks=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        let search=fields.search;
        let auth=fields.auth;
        let pageSize=parseInt(fields.pageSize);
        let currentPage=parseInt(fields.currentPage)-1;
        let pagenum=pageSize*currentPage;
        let re = new RegExp(search);
        let re1=new RegExp(auth);
        let obj={};
        if(search&&auth){
            obj={bName:re,bAuth:re1};
        }else if(search==""&&auth){
            obj={bAuth:re1};
        }else if(search&&auth==""){
            obj={bName:re};
        }
        // console.log(fields);
        let p1=new Promise(function(resolve,reject){
            BookModel.findLimitSkip(obj,pageSize,pagenum,{bid:1},function(err,docs){
                if(err){
                    reject(err);
                }else{
                    resolve(docs);
                }
            });
        });
        p1.then(function(docs){
            BookModel.findConut(obj,function(err,count){
                if(err){
                    res.json({code:0,msg:"失败",info:[]});
                    return false;
                }
                res.json({code:1,msg:"成功",info:docs,count:count});
            });
        },function(err){
            res.json({code:0,msg:"失败",info:[]});
        });
    });
};
exports.getAllBookInfo=function(req,res){
    var p1=new Promise(function(resolve,reject){
        CategorysModel.findFn({},function(err,docs){
            if(err){
                reject(err);
            }else{
                resolve(docs);
            }
        });
    });
    p1.then(function(result){
        AuthorModel.findFn({},{cid:1},function(err,docs){
           if(err){
               res.json({code:0,msg:"失败",info:[]});
           }
           res.json({code:1,msg:"成功",info:{cats:result,authors:docs}});
        });

    },function(err){
        res.json({code:0,msg:"失败",info:[]});
    });
};
exports.getSubCate=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        let catid=parseInt(fields.cat);
        SubcateModel.findFn({cgid:catid},{scid:1},function(err,docs){
            if(err){
                res.json({code:0,msg:"失败",info:[]});
            }
            res.json({code:1,msg:"成功",info:docs});
        });
    });
};
exports.getAuthors=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files) {
        let auth = fields.auth;
        let pageSize = parseInt(fields.pageSize);
        let currentPage = parseInt(fields.currentPage) - 1;
        let pagenum = pageSize * currentPage;
        let re1 = new RegExp(auth);
        let obj={};
        if(auth!=""){
            obj={bAuth:re1};
        }
        let p1=new Promise(function(resolve,reject){
            AuthorModel.findLimitSkip(obj,pageSize,pagenum,{cid:1},function(err,docs){
                if(err){
                    reject(err);
                }else{
                    resolve(docs);
                }
            });
        });
        p1.then(function(docs){
            AuthorModel.findConut(obj,function(err,count){
                if(err){
                    res.json({code:0,msg:"失败",info:[]});
                    return false;
                }
                res.json({code:1,msg:"成功",info:docs,count:count});
            });
        },function(err){
            res.json({code:0,msg:"失败",info:[]});
        });
    });
};
exports.setAddBook=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
       let {name,isvip,status,cat,catName,subCate,subCateName,stateType,bAuth,authorName,desc,date}=fields;
        BookModel.findSortOne({},{bid:-1},function(err,doc){
            let obj={
                bid:parseInt(doc.bid)+1,
                bName:name,
                desc:desc,
                catId:parseInt(cat),
                cat:catName,
                subCateId:parseInt(subCate),
                subCateName:subCateName,
                cid:parseInt(bAuth),
                bAuth:authorName,
                stateType:stateType,
                signStatus:status,
                isVip:parseInt(isvip),
                startTime:new Date(date).getTime(),
                lable:[]
            };
            let data=new BookModel(obj);
            data.save(function(err){
                fs.mkdirSync('./public/up/data/book/'+(parseInt(doc.bid)+1));
                res.json({code:1,msg:"成功"});
            });
        });
    });
};
exports.setAddAuthor=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        let {name,grade,desc}=fields;
        AuthorModel.findSortOne({},{cid:-1},function(err,doc){
            let obj={
                cid:parseInt(doc.cid)+1,
                bAuth:name,
                desc:desc,
                grade:grade
            };
            let data=new AuthorModel(obj);
            data.save(function(err){
                res.json({code:1,msg:"成功"});
            });
        });
    });
};
exports.authorUpdateImg=function(req,res){
    let form=new formidable.IncomingForm();
    form.uploadDir='./public/up/images/head/';
    form.parse(req,function(err,fields,files){
        let cid=parseInt(fields.cid);
            var ttt=new Date().getTime();
            //随机数
            var ran=parseInt(Math.random()*89999+10000);
            //后缀名
            var extname=path.extname(files['file'].name);
            //旧文件名
            var oldpath="./"+files['file'].path;
            //新文件名
            var newpath="./public/up/images/head/"+ttt+ran+extname;
            let authorpath="/up/images/head/"+ttt+ran+extname;
            // console.log(oldpath);
            // console.log(newpath);
            let p1=new Promise(function(resolve,reject){
                fs.rename(oldpath,newpath,function(err){
                    if(err){
                        reject(err);
                        return;
                    }else{
                        resolve(true);
                    }
                });
            });
            p1.then(function(result){
                // gm(newpath)
                //     .resize(100, 100)
                //     .write(newpath, function (err) {
                //         if (!err) {
                //            res.json({code:1,msg:"成功",url:authorpath});
                //         }else{
                //          console.log(err);
                //         }
                //     });

                AuthorModel.updateFn({cid:cid},{$set:{"imgurl":authorpath}},function(err,res1){
                    if(err){
                        res.json({code:2,msg:"图片写入数据库失败"});
                    }

                    res.json({code:1,msg:"图片上传成功",url:authorpath});
                });
            },function(err){
                res.json({code:2,msg:"图片名字修改失败"});
            });
    });
};
exports.setEditAuthor=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        let {bAuth,grade,desc,cid}=fields;
        AuthorModel.updateFn({cid:cid},{$set:{bAuth:bAuth,grade:grade,desc:desc}},function(err,doc){
            if(err){
                res.json({code:0,msg:"修改失败"});
                return;
            }
            res.json({code:1,msg:"修改成功"});
        });
    });
};
exports.removeAuthor=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        let {cid,imgurl}=fields;
        AuthorModel.removeFn({cid:cid},function(err,doc){
            if(err){
                res.json({code:0,msg:"删除失败"});
                return;
            }
            if(imgurl=="/up/images/head/head.png"){
                res.json({code:1,msg:"删除成功"});
            }else{
                fs.unlink("./public"+imgurl,function(err){
                    res.json({code:1,msg:"删除成功"});
                });
            }
        });
    });
};
exports.BookUpdateImg=function(req,res){
    let form=new formidable.IncomingForm();
    form.uploadDir='./public/up/images/book/';
    form.parse(req,function(err,fields,files){
        let bid=parseInt(fields.bid);
        var ttt=new Date().getTime();
        //随机数
        var ran=parseInt(Math.random()*89999+10000);
        //后缀名
        var extname=path.extname(files['file'].name);
        //旧文件名
        var oldpath="./"+files['file'].path;
        //新文件名
        var newpath="./public/up/images/book/"+ttt+ran+extname;
        let authorpath="/up/images/book/"+ttt+ran+extname;
        // console.log(oldpath);
        // console.log(newpath);
        let p1=new Promise(function(resolve,reject){
            fs.rename(oldpath,newpath,function(err){
                if(err){
                    reject(err);
                    return;
                }else{
                    resolve(true);
                }
            });
        });
        p1.then(function(result){
            // gm(newpath)
            //     .resize(100, 100)
            //     .write(newpath, function (err) {
            //         if (!err) {
            //            res.json({code:1,msg:"成功",url:authorpath});
            //         }else{
            //          console.log(err);
            //         }
            //     });

            BookModel.updateFn({bid:bid},{$set:{"imgurl":authorpath}},function(err,res1){
                if(err){
                    res.json({code:2,msg:"图片写入数据库失败"});
                }
                res.json({code:1,msg:"图片上传成功",url:authorpath});
            });
        },function(err){
            res.json({code:2,msg:"图片名字修改失败"});
        });
    });
};
exports.removeBook=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        let {bid,imgurl}=fields;
        BookModel.removeFn({bid:bid},function(err,doc){
            if(err){
                res.json({code:0,msg:"删除失败"});
                return;
            }
            if(imgurl=="/up/images/book/bookimg.png"){
                try{
                    fs.readdirSync('./public/up/data/book/'+bid);
                }catch(err){
                    fs.mkdirSync('./public/up/data/book/'+bid);
                }
                deleteall('./public/up/data/book/'+bid);
                res.json({code:1,msg:"删除成功"});
            }else{
                fs.unlink("./public"+imgurl,function(err){
                    try{
                        fs.readdirSync('./public/up/data/book/'+bid);
                    }catch(err){
                        fs.mkdirSync('./public/up/data/book/'+bid);
                    }
                    deleteall('./public/up/data/book/'+bid);
                    res.json({code:1,msg:"删除成功"});
                });
            }
        });
    });
};
exports.setEditBook=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        let {bid,name,isvip,status,cat,catName,subCate,subCateName,stateType,bAuth,authorName,desc,date}=fields;
        BookModel.updateFn({bid:parseInt(bid)},{$set:{
            bName:name,
            desc:desc,
            catId:parseInt(cat),
            cat:catName,
            subCateId:parseInt(subCate),
            subCateName:subCateName,
            cid:parseInt(bAuth),
            bAuth:authorName,
            stateType:stateType,
            signStatus:status,
            isVip:parseInt(isvip),
            startTime:new Date(date).getTime()
        }},function(err,doc){
            if(err){
                res.json({code:0,msg:"失败"});
                return;
            }
            res.json({code:1,msg:"修改成功"});
        });
    });
};
exports.getSelectBooks=function(req,res){
    BookModel.findFnSmall({},{bid:1,bName:1},{bid:1},function(err,docs){
        if(err){
            res.json({code:0,msg:"获取数据失败"});
            return;
        }
        res.json({code:1,msg:"获取书籍成功",info:docs});
    });
};
exports.getChapters=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        let bid=parseInt(fields.bid);
        let chapter=fields.chapter;
        let currentPage=parseInt(fields.currentPage)-1;
        let pageSize=parseInt(fields.pageSize);
        let pagenum=pageSize*currentPage;
        let re = new RegExp(chapter);
        let obj={};
        if(bid==0&&chapter==""){
            obj={};
        }else if(bid!=0&&chapter==""){
            obj={bid:bid};
        }else if(bid==0&&chapter!=""){
            obj={title:re};
        }else if(bid!=0&&chapter!=""){
            obj={bid:bid,title:re};
        }
        let p1=new Promise(function(resolve,reject){
            BookupdateModel.findLimitSkip(obj,pageSize,pagenum,{buid:-1},function(err,docs){
                if(err){
                    reject(err);
                }else{
                    resolve(docs);
                }
            });
        });
        p1.then(function(docs){
            let count=BookupdateModel.findConut(obj,function(err,count){
                if(err) {
                    res.json({code: 0, msg: "失败", info: [], count: 0});
                    return false;
                }
            });
            return {docs:docs,count:count};
        },function(err){
            res.json({code:0,msg:"失败",info:[],count:0});
        }).then(function(result){
            let bArr=[];
            let fsDesc=[];
            (function bl(i){
                i++;
                if(i==result.docs.length){
                    res.json({code:1,msg:"成功",info:result.docs,count:result.count,bArr:bArr,fsDesc:fsDesc});
                    return;
                }else{
                    BookModel.findOneSmall({
                        bid:result.docs[i]['bid']
                    },
                    {
                        bName:1,
                        bAuth:1,
                        cid:1
                    },{
                        bid:1
                    },function(err,doc){
                        if(err){
                            res.json({code:0,msg:"失败",info:[],count:0});
                        }
                        bArr.push(doc);
                        let desc=fs.readFileSync('./public'+result.docs[i]['src']);
                        fsDesc.push(desc.toString());
                        bl(i);
                    })
                }
            })(-1);
        })
    })
};
exports.setAddChapter=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files){
        let bid=parseInt(fields.bid);
        let {title,desc,date}=fields;
        let p1=new Promise(function (resolve,reject){
            BookupdateModel.findSortOne({bid:bid},{chapters:-1},function(err,doc){
                if(err){
                    reject(err);
                }else{
                    resolve(doc);
                }
            })
        });
        p1.then(function(doc){
            if(doc==null||doc=={}){
                BookupdateModel.findSortOne({},{buid:-1},function(err,result){
                    let src="/up/data/book/"+bid+"/1.txt";
                    let obj={
                        buid:parseInt(result.buid)+1,
                        bid:bid,
                        chapters:1,
                        updateTime:new Date(date).getTime(),
                        title:title,
                        src:src
                    };
                    try{
                        fs.readdirSync('./public/up/data/book/'+bid);
                    }catch(err){
                        fs.mkdirSync('./public/up/data/book/'+bid);
                    }
                    fs.writeFileSync("./public"+src,desc);
                    let data=new BookupdateModel(obj);
                    data.save(function(err){
                        BookModel.updateFn({bid:bid},{$set:{
                            updateTime:new Date(date).getTime(),
                            lastUpdateTime:new Date(date).getTime(),
                            updateTitle:title,
                            cnt:desc.replace(/<[^<]+>/g,'').length,
                        }},function(err,result1){
                            if(err){
                                res.json({code:0,msg:"新增章节失败"})
                            }else{
                                res.json({code:1,msg:"新增章节成功"})
                            }
                        });
                    })
                });
            }else{
                BookupdateModel.findSortOne({},{buid:-1},function(err,result){
                    let src="/up/data/book/"+bid+"/"+(parseInt(doc.chapters)+1)+".txt";
                    let obj={
                        buid:parseInt(result.buid)+1,
                        bid:bid,
                        chapters:parseInt(doc.chapters)+1,
                        updateTime:new Date(date).getTime(),
                        title:title,
                        src:src
                    };
                    try{
                        fs.readdirSync('./public/up/data/book/'+bid);
                    }catch(err){
                        fs.mkdirSync('./public/up/data/book/'+bid);
                    }
                    fs.writeFileSync("./public"+src,desc);
                    let data=new BookupdateModel(obj);
                    data.save(function(err){
                        BookModel.findSortOne({bid:bid},{bid:1},function(err,br1){
                            BookModel.updateFn({bid:bid},{$set:{
                                updateTime:new Date(date).getTime(),
                                lastUpdateTime:new Date(date).getTime(),
                                updateTitle:title,
                                cnt:parseInt(br1.cnt)+(desc.replace(/<[^<]+>/g,'').length)
                            }},function(err,result1){
                                if(err){
                                    res.json({code:0,msg:"新增章节失败"})
                                }else{
                                    res.json({code:1,msg:"新增章节成功"})
                                }
                            });
                        });
                    })
                });
            }
        },function(err){
            res.json({code:0,msg:"新增章节失败"})
        });
    });
};
exports.setEditChapter=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files) {
        let bid=parseInt(fields.bid);
        let buid=parseInt(fields.buid);
        let {title, desc, date} = fields;
        var p1=new Promise(function(resolve,reject){
            //修改章节
            BookupdateModel.updateFn({buid:buid,bid:bid},{$set:{title:title,updateTime:new Date(date).getTime()}},function(err,result){
                if(err){
                    reject(err);
                    return;
                }else{
                    resolve(result);
                }
            })
        });
        p1.then(function(result){
            //获取章节
            BookupdateModel.findSortOne({buid:buid},{buid:1},function(err,res1){
                if(err){
                    res.json({code:2,msg:"修改内容失败"});
                    return;
                }
                //获取旧内容
                let file=fs.readFileSync('./public'+res1.src);
                //旧内容的长度
                let length=file.toString().replace(/<[^<]+>/g,'').length;
                BookModel.findSortOne({bid:bid},{bid:1},function(err,br1){
                    if(err){
                        res.json({code:2,msg:"修改内容失败"});
                        return;
                    }
                    //所有长度减去旧内容长度，减去内容得的长度
                    let le=br1.cnt-length;
                    //获取是否最后章节
                    BookupdateModel.findSortOne({bid:bid},{chapters:-1},function(err,res2){
                        if(res1.chapters==res2.chapters){
                            //修改书本的信息
                            BookModel.updateFn({bid:bid},{$set:{
                                updateTime:new Date(date).getTime(),//更新最新时间
                                lastUpdateTime:new Date(date).getTime(),//更新更新时间
                                updateTitle:title,        //更新章节名
                                cnt:le+(desc.replace(/<[^<]+>/g,'').length)  //减去内容得的长度加新内容长度
                            }},function(err,result1){
                                if(err){
                                    res.json({code:0,msg:"修改章节失败"});
                                    return;
                                }else{
                                    //修改内容
                                    fs.writeFileSync("./public"+res1.src,desc);
                                    res.json({code:1,msg:"修改章节成功"})
                                }
                            });
                        }else{
                            //修改书本的信息
                            BookModel.updateFn({bid:bid},{$set:{
                                cnt:le+(desc.replace(/<[^<]+>/g,'').length)  //减去内容得的长度加新内容长度
                            }},function(err,result1){
                                if(err){
                                    res.json({code:0,msg:"修改章节失败"});
                                    return;
                                }else{
                                    //修改内容
                                    fs.writeFileSync("./public"+res1.src,desc);
                                    res.json({code:1,msg:"修改章节成功"})
                                }
                            });
                        }
                    });
                })
            })
        },function(err){
            res.json({code:0,msg:"修改章节失败"})
        })
    });
};
exports.removeChapter=function(req,res){
    let form=new formidable.IncomingForm();
    form.parse(req,function(err,fields,files) {
        let bid = parseInt(fields.bid);
        let buid = parseInt(fields.buid);
        let {title, desc, date} = fields;
        BookupdateModel.findSortOne({buid:buid},{buid:1},function(err,res1){
            //获取旧内容
            let file=fs.readFileSync('./public'+res1.src);
            //旧内容的长度
            let length=file.toString().replace(/<[^<]+>/g,'').length;
            BookModel.findSortOne({bid:bid},{bid:1},function(err,br1) {
                if (err) {
                    res.json({code: 0, msg: "删除章节失败"});
                    return;
                }
                //所有长度减去旧内容长度，减去内容得的长度
                let le = br1.cnt - length;
                //删除章节
                BookupdateModel.removeFn({buid:buid},function(err,result){
                    if (err) {
                        res.json({code: 0, msg: "删除章节失败"});
                        return;
                    }
                    //获取最后的章节
                    BookupdateModel.findSortOne({bid:bid},{chapters:-1},function(err,res2){
                        //修改书本的信息
                        BookModel.updateFn({bid:bid},{$set:{
                            updateTime:res2.updateTime,//更新最新时间
                            lastUpdateTime:res2.updateTime,//更新更新时间
                            updateTitle:res2.title,        //更新章节名
                            cnt:le  //减去内容得的长度
                        }},function(err,result1){
                            if(err){
                                res.json({code:0,msg:"删除章节失败"});
                                return;
                            }else{
                                fs.unlinkSync('./public'+res1.src);
                                res.json({code:1,msg:"删除章节成功"})
                            }
                        });
                    });
                })
            })
        })
    })
};
exports.setAddMenuOne=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let {title,path,iconClass,type}=fields;
        SystemmenuModel.findSortOne({},{smid:-1},function(err,doc){
            if(err){
                res.json({code:0,msg:"新建一级菜单失败"});
                return;
            }
            let obj={
                smid:parseInt(doc.smid)+1,
                type:type,
                title:title,
                path:path,
                iconClass:iconClass,
                createTime:new Date().getTime()
            };
            let data=new SystemmenuModel(obj);
            data.save(function(err){
                if(err){
                    res.json({code:0,msg:"新建一级菜单失败"});
                    return;
                }
                res.json({code:1,msg:"新建一级菜单成功"})
            })
        });
    });
};
exports.removeSystemMenu=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let grade=parseInt(fields.grade);
        let smid=parseInt(fields.smid);
        let ssmid=parseInt(fields.ssmid);
        if(grade==1){
            SystemsubmenuModel.removeFn({smid:smid},function(err,doc){
                if(err){
                    res.json({code:2,msg:"删除子级菜单失败"});
                }
                SystemmenuModel.removeFn({smid:smid},function(err,doc){
                    if(err){
                        res.json({code:0,msg:"删除菜单失败"});
                    }
                    res.json({code:1,msg:"删除菜单成功"});
                })
            });
        }else if(grade==2){
            SystemsubmenuModel.removeFn({ssmid:ssmid},function(err,doc){
                if(err){
                    res.json({code:2,msg:"删除子级菜单失败"});
                }
                res.json({code:1,msg:"删除子菜单成功"});
            })
        }
    });
};
exports.setAddMenuTwo=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let smid=parseInt(fields.smid);
        let {title,path,iconClass,type}=fields;
        SystemsubmenuModel.findSortOne({},{ssmid:-1},function(err,doc){
            if(err){
                res.json({code:0,msg:"新建二级菜单失败"});
                return;
            }
            let obj={
                ssmid:parseInt(doc.ssmid)+1,
                smid:smid,
                type:type,
                title:title,
                path:path,
                iconClass:iconClass,
                createTime:new Date().getTime()
            };
            let data=new SystemsubmenuModel(obj);
            data.save(function(err){
                if(err){
                    res.json({code:0,msg:"新建二级菜单失败"});
                    return;
                }
                res.json({code:1,msg:"新建二级菜单成功"})
            })
        });
    })
};
exports.editSystemMenu=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let grade=parseInt(fields.grade);
        let title=fields.title;
        let path=fields.path;
        let type=fields.type;
        let iconClass=fields.iconClass;
        let smid=parseInt(fields.smid);
        let ssmid=parseInt(fields.ssmid);
        if(grade==1){
            SystemmenuModel.updateFn({smid:smid},{$set:{
                title:title,
                path:path,
                type:type,
                iconClass:iconClass
            }},function(err,doc){
                if(err){
                    res.json({code:0,msg:"修改菜单失败"});
                }
                res.json({code:1,msg:"修改菜单成功"});
            });
        }else if(grade==2){
            SystemsubmenuModel.updateFn({ssmid:ssmid},{$set:{
                title:title,
                path:path,
                type:type,
                iconClass:iconClass
            }},function(err,doc){
                if(err){
                    res.json({code:0,msg:"修改子级菜单失败"});
                }
                res.json({code:1,msg:"修改子菜单成功"});
            })
        }
    });
};